package com.zmj.mobile.controller;

import com.zmj.framework.response.Result;
import com.zmj.mobile.dto.OrgVO;
import com.zmj.mobile.dto.OrgUserVO;
import com.zmj.mobile.dto.UserVO;
import com.zmj.mobile.mapstruct.OrgMapStruct;
import com.zmj.mobile.mapstruct.UserMapStruct;
import com.zmj.mobile.entity.OrgEntity;
import com.zmj.mobile.entity.OrgUserEntity;
import com.zmj.mobile.entity.UserEntity;
import com.zmj.mobile.service.IOrgService;
import com.zmj.mobile.service.IOrgUserService;
import com.zmj.mobile.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @DATE 2024/2/1 20:27
 * @AUTHOR zhaizongwei
 */
@RestController
@Api(tags = {"OrgUser"})
@RequestMapping("/v1/api/org/user")
public class OrgUserController {

    @Resource
    private IOrgService iOrgService;

    @Resource
    private IOrgUserService iOrgUserService;

    @Resource
    private IUserService iUserService;

    /**
     * 查询部门
     *
     * @param orgCode 入参
     * @return 出参
     */
    @GetMapping("/org/list")
    @ApiOperation(value = "/org/list")
    public Result<?> orgList(@RequestParam String orgCode) {

        List<OrgEntity> orgEntityList = iOrgService.getListByParentId(orgCode);

        return Result.success(OrgMapStruct.INSTANCE.toVOList(orgEntityList));
    }

    /**
     * 查询部门和人员
     *
     * @param orgCode 入参
     * @return 出参
     */
    @GetMapping("/user/list")
    @ApiOperation(value = "/user/list")
    public Result<?> userList(@RequestParam String orgCode) {

        OrgUserVO orgUserVO = new OrgUserVO();

        //查询下属部门
        List<OrgEntity> orgEntityList = iOrgService.getListByParentId(orgCode);
        List<OrgVO> orgVOList = OrgMapStruct.INSTANCE.toVOList(orgEntityList);
        orgUserVO.setOrgVOList(orgVOList);

        //查询当前部门信息
        OrgEntity thisOrgEntity = iOrgService.getOneByCode(orgCode);

        if (Objects.isNull(thisOrgEntity)) {
            return Result.success(orgUserVO);
        }

        //根据部门信息查询所属人员
        List<OrgUserEntity> orgUserEntityList = iOrgUserService.getByOrgId(thisOrgEntity.getId());
        List<Integer> userIdList = orgUserEntityList.stream().map(OrgUserEntity::getUserId).collect(Collectors.toList());
        //根据人员id查询人员信息
        List<UserEntity> userEntityList = iUserService.getListById(userIdList);
        List<UserVO> userVOList = UserMapStruct.INSTANCE.toDTOList(userEntityList);
        orgUserVO.setUserVOList(userVOList);

        return Result.success(orgUserVO);
    }
}
